use serde::Deserialize;
use std::{collections::HashMap, fs, io};

/// 从资源中生成汉语拼音->威妥玛翻译器.
pub fn read_wade_resource() -> WadeGilesTranslator {
    let file_path = "pinyin_mapping.xml";
    let file = fs::File::open(file_path).unwrap();
    let reader = io::BufReader::new(file);

    let mappings: PinyinMapping = quick_xml::de::from_reader(reader).unwrap();

    let mut result: HashMap<String, String> = HashMap::new();
    for one_item in mappings.item {
        // 需要使用单引号
        let processed_wade = one_item.wade.replace('`', "'");
        result.insert(one_item.hanyu, processed_wade);
    }

    WadeGilesTranslator::with_map(result)
}

#[derive(Debug, Deserialize)]
struct PinyinMapping {
    item: Vec<Item>,
}

#[derive(Debug, Deserialize)]
#[serde(rename = "item")]
struct Item {
    #[serde(rename = "Hanyu")]
    hanyu: String,
    #[serde(rename = "Wade")]
    wade: String,
}

/// 把汉语拼音翻译成威妥玛的翻译器.
pub struct WadeGilesTranslator {
    trans_map: HashMap<String, String>,
}

impl WadeGilesTranslator {
    /// 使用完整数据初始化翻译器.
    pub fn with_map(map: HashMap<String, String>) -> Self {
        Self { trans_map: map }
    }

    /// 把汉语拼音翻译成威妥玛.
    pub fn trans_pinyin(&self, pinyin: &str) -> Option<&str> {
        self.trans_map.get(pinyin).map(|s| s.as_ref())
    }
}

// mod tests {
//     #[allow(unused_imports)]
//     use super::*;

//     #[test]
//     fn test_wade() {
//         let wg_translator = read_wade_resource();
//         assert_eq!(wg_translator.trans_pinyin("zui").unwrap(), "tsui");
//         assert_eq!(wg_translator.trans_pinyin("chuan").unwrap(), "ch'uan");
//         assert_eq!(wg_translator.trans_pinyin("si").unwrap(), "ssu");
//     }
// }
